<?php
namespace app\erp\model;

use think\Model;

class StaffAccessdb extends Model
{

    protected $pk = 'staff_access_id';

    protected $name = 'staffAccess';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    public $param = array();

    public function scopeStaffId($query, $staff_id)
    {
        $query->where('staff_id', $staff_id);
    }

    public function base($query)
    {
        if (isset($this->param['staff_id']) && $this->param['staff_id']) {
            $query->staffId($this->param['staff_id']);
        }
    }

    public function ajaxSave()
    {
        $staff_access_id = $this->ajaxFind();
        $access_option = array();
        foreach ($this->param['config_value'] as $key => $val) {
            if ($key != 'staff_id') {
                array_push($access_option, $key);
            }
        }
        unset($this->param['config_value']);
        $this->param['access_option'] = implode(',', $access_option);
        if ($staff_access_id == 0) {
            // 新增
            $this->save($this->param);
        } else {
            // 修改
            $this->save($this->param, [
                'staff_access_id' => $staff_access_id
            ]);
        }
        return 'success';
    }

    public function ajaxFind()
    {
        $data = $this->master(true)->find();
        if ($data) {
            $data = $data->toArray();
            return $data['staff_access_id'];
        } else {
            return 0;
        }
    }
    public function getAccessOption(){
        $data = $this->master(true)->find();
        if ($data) {
            $data = $data->toArray();
            $access_option = explode(',', $data['access_option']);
            for($i=0;$i<count($access_option);$i++){
                $access_option[$i] = url($access_option[$i]);
            }
            return $access_option;
        } else {
            return array();
        }
    }

    public function getAccess()
    {
        $data = $this->master(true)->find();
        if ($data) {
            $data = $data->toArray();
            $access_option = explode(',', $data['access_option']);
            $return = array();
            for($i=0;$i<count($access_option);$i++){
                $return[$access_option[$i]] = true;
            }
            return $return;
        } else {
            return array();
        }
    }
}